<template>
  <div class="app-container role-edit">
    <el-row class="user-form">
      <el-form ref="editUserForm" :model="editUserForm" class="edit-user el-form-box-left" label-width="87px">
        <div class="form-box">
          <Title :title="'权限设置'" style="padding: 32px 0;flex: 1"/>
          <el-form-item label="矩阵权限：">
            <el-select
              :disabled="!isBrandAdmin()"
              v-model="editUserForm.matrixRole"
              popper-class="global-select-down"
              filterable
              multiple
              clearable
              size="small"
              placeholder="请选择"
              class="role-input">
              <el-option
                v-for="item in matrixOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="账号选择：">
            <el-select
              :disabled="!isBrandAdmin() && !isHead"
              v-model="editUserForm.resourceRole"
              :multiple-limit="50"
              :remote-method="getPageList"
              popper-class="global-select-down"
              filterable
              clearable
              multiple
              size="small"
              remote
              reserve-keyword
              placeholder="请选择"
              class="role-input"
              @visible-change="getPageList('')">
              <el-option
                v-for="item in resourceOptionsByFilter.items"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
              <div v-show="resourceOptionsByFilter.total > resourceOptionsByFilter.pageSize" class="role-page-line"/>
              <el-pagination
                v-show="resourceOptionsByFilter.total > resourceOptionsByFilter.pageSize"
                :current-page="resourceOptionsByFilter.page"
                :page-size="resourceOptionsByFilter.pageSize"
                :total="resourceOptionsByFilter.total"
                layout="total, prev, pager, next, jumper"
                small
                class="role-page-style"
                @current-change="getPageListByPage" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item class="crm-add-btn">
          <el-button :loading="loading" type="primary" class="submit-btn" @click="toSave">保存</el-button>
          <el-button type="info" class="back-btn" @click="toClear">取消</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { getMatrix, getAccout, getRole, roleEdit } from '@/api/brand';
import { isBrandAdmin } from '@/utils/permission';
import Title from '@/components/Title';

export default {
  components: { Title },
  data() {
    return {
      editUserForm: {
        matrixRole: [],
        resourceRole: []
      },
      matrixOptions: [],
      resourceOptions: [],
      resourceOptionsByFilter: {
        items: [],
        page: -1,
        pageSize: 20,
        total: -1
      },
      query: '',
      loading: false,
      userId: null,
      isHead: false,
      isOrdinary: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    this.userId = Number(this.$route.params.roleId) || null;
    this.load();
  },
  methods: {
    isBrandAdmin,
    load() {
      Promise.all([this.getMatrix(), this.getAccout(), this.getInfo()]).then(() => {
        const resourceRole = this.editUserForm.resourceRole;
        if (resourceRole && resourceRole.length > 0) { // 过滤已选值，避免只显示id
          const options = this.resourceOptions.filter(item => {
            return resourceRole.some(i => i === item.id);
          });
          this.resourceOptionsByFilter = {
            items: options,
            page: 1,
            pageSize: 20,
            total: options.length
          };
        } else {
          this.getPageListByPage();
        }
      });
      this.isHead = Number(this.$route.query.isHead);
    },
    getPageListByPage(page) {
      this.getPageList(this.query, page);
    },
    getPageList(query, page = 1) {
      this.query = query;
      let options;
      if (query !== '') {
        options = this.resourceOptions.filter(item => { // 获取所有符合条件的选项
          return item.name.toLowerCase()
            .indexOf(query.toLowerCase()) > -1;
        });
      } else {
        options = this.resourceOptions;
      }
      const start = page > 1 ? (page - 1) * this.resourceOptionsByFilter.pageSize : 0;
      const end = start + this.resourceOptionsByFilter.pageSize;
      this.resourceOptionsByFilter = {
        items: options.slice(start, end),
        page,
        pageSize: 20,
        total: options.length
      };
    },
    getMatrix() { // 获取矩阵列表
      return getMatrix().then(res => {
        this.matrixOptions = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    getAccout() { // 获取账号列表
      return getAccout().then(res => {
        this.resourceOptions = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    getInfo() { // 获取用户权限信息
      return getRole(this.userId).then(res => {
        res.data.matrixRole = res.data.matrixRole.map(item => {
          return item.id;
        });
        res.data.resourceRole = res.data.resourceRole.map(item => {
          return item.id;
        });
        this.editUserForm = res.data;
      }, result => {
        // this.$message.error(result.message);
      });
    },
    getData(arr) { // 获取修改账号权限的对象
      const newArr = [];
      let obj = {};
      arr.forEach(item => {
        obj = this.resourceOptions.find(val => {
          return val.id === item;
        });
        newArr.push(obj);
      });
      return newArr;
    },
    toSave() {
      const editUserForm = {
        matrixRole: JSON.stringify(this.editUserForm.matrixRole),
        resourceRole: JSON.stringify(this.editUserForm.resourceRole)
      };
      this.loading = true;
      roleEdit(this.userId, editUserForm).then(res => {
        this.loading = false;
        localStorage.setItem('isSuccess', true);
        // 缓存后返回列表
        this.editUserForm.accountList = this.getData(this.editUserForm.resourceRole);
        localStorage.setItem('changeData', JSON.stringify(this.editUserForm));
        this.$message.success('修改成功');
        this.$router.push({
          name: 'userList'
        });
      }, result => {
        this.loading = false;
        // this.$message.error(result.message);
      });
    },
    toClear() {
      localStorage.setItem('isSuccess', false);
      localStorage.setItem('changeData', '');
      this.$router.push({
        name: 'userList'
      });
    }
  }
};
</script>
<style lang="scss">
.role-edit {
  padding: 0 21px 31px 0;
  .user-form {
    margin: 20px 20px 0 20px;
    background-color: #FBFBFD;
    .form-box {
      box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
      border-radius:12px;
      padding-left: 32px;
      padding-bottom: 32px;
      background-color: #fff;
      height: 640px;;
    }
  }
  .edit-user {
    .form-box {
      .el-form-item {
        margin-bottom: 20px !important;
        .el-form-item__label {
          font-size: 13px !important;
        }
        .role-input {
          width: 600px;
        }
        .el-select__tags-text {
          color: #666;
        }
      }
    }
    .crm-add-btn {
      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }
}

.role-page-line {
  /*float: right;*/
  margin: 0 10px;
  border-top: 1px solid #DCDFE6;
}
.role-page-style {
  float: right;
  margin: 0 10px;
  /*border-top: 1px solid #DCDFE6;*/
}
.el-select-dropdown.is-multiple .el-select-dropdown__item.selected {
  border-radius: 19px;
}
.el-select__input { // 防止下拉框抖动
  vertical-align: baseline;
}
// .el-select-dropdown {
//   vertical-align: baseline;
// }
</style>
